package psn.zjk.common.utils;

import java.util.concurrent.*;

/**
 * @Description
 * @User zero
 * @Datetime 2021/6/4 19:54
 */
public class AsynWithThreadLocal {

    //    子线程可以获取
    private InheritableThreadLocal<String> local = new InheritableThreadLocal<>();
    //子线程获取不到
//    private ThreadLocal<String> local = ThreadLocal.withInitial(() -> {
//        return "";
//    });

    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
        CountDownLatch countDownLatch = new CountDownLatch(1);
        AsynWithThreadLocal asynWithThreadLocal = new AsynWithThreadLocal();
        asynWithThreadLocal.send(Thread.currentThread().getName());
        new Thread(() -> {
            asynWithThreadLocal.receive();
            asynWithThreadLocal.send(Thread.currentThread().getName());
            countDownLatch.countDown();

        }).start();
        countDownLatch.await();
        //这里可以发现获取到的和子线程塞入的不一致
        asynWithThreadLocal.receive();

        ArrayBlockingQueue<String> arrayBlockingQueue = new ArrayBlockingQueue<>(1);
        //可以用CompletableFuture,更强大，子线程传给父线程
        CompletableFuture<String> future =  CompletableFuture.supplyAsync(arrayBlockingQueue::poll);
        new Thread(() -> {
            try {
                arrayBlockingQueue.put("child");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        System.out.println("CompletableFuture=========="+future.get(5, TimeUnit.SECONDS));
    }


    public void send(String name) {
        local.set(name);
        System.out.println(Thread.currentThread().getName() +"设置");
    }

    public void receive() {
        System.out.println(Thread.currentThread().getName() + "===" + local.get());
    }

}
